package com.person.monitor;

import android.os.Handler;
import android.os.Looper;
import org.greenrobot.eventbus.EventBus;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class LogcatHelper {

    private static LogcatHelper logcatHelper = new LogcatHelper();

    private List<String> logList = new ArrayList<>();

    private WriteLogThread writeLogThread;

    private LogcatHelper(){
        if(BuildConfig.DEBUG) {
            (writeLogThread = new WriteLogThread()).start();
        }
    }

    public synchronized static LogcatHelper getInstance(){
        return logcatHelper;
    }

    public void printLog(String log){
        //String logString = getLogTime() +":"+ log;

        String logString = log;

        logList.add(0,logString);

        if(logList.size() > 1000){
            logList.remove(logList.size() - 1);
        }

        if(writeLogThread != null) writeLogThread.writeLog(logString);

        EventBus.getDefault().post(new EventMessage(EventMessage.EVENT_NEW_LOG));
    }

    public static String getLogTime() {
        Date date = new Date();

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");

        String time = format.format(date);

        return time;
    }

    public List<String> getLogList(){
        return logList;
    }

    public class WriteLogThread extends Thread{
        private FileOutputStream out = null;
        private String mLogFilePath;
        private String mDir;
        private Handler handler;

        public WriteLogThread(){
            mDir = "/sdcard/Monitor";
        }

        @Override
        public void run() {
            try {
                File dir = new File(mDir);

                if(!dir.exists()){
                    dir.mkdir();
                }

                mLogFilePath = mDir + File.separator  + System.currentTimeMillis();

                out = new FileOutputStream(new File(mLogFilePath));

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            Looper.prepare();
            handler = new Handler(Looper.myLooper());
            Looper.loop();
        }

        public void writeLog(String log) {
            if (handler != null)
                handler.post(() -> {
                    if (out != null) {
                        try {
                            out.write((log + "\n").getBytes());
                            out.flush();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });
        }
    }

}
